using System;
using System.Threading.Tasks;
using UnityEngine;
using RPG.Infrastructure.Core;
using Newtonsoft.Json;

namespace RPG.Infrastructure.Persistence
{
    public class UnityRepository<TAggregate, TId> : IRepository<TAggregate, TId> 
        where TAggregate : AggregateRoot<TId>
    {
        private readonly string _storageKey;
        
        public UnityRepository(string aggregateTypeName)
        {
            _storageKey = $"RPG_{aggregateTypeName}_";
        }

        public async Task<TAggregate> GetByIdAsync(TId id)
        {
            var key = _storageKey + id.ToString();
            var json = PlayerPrefs.GetString(key, null);
            
            if (string.IsNullOrEmpty(json))
                return null;

            return await Task.FromResult(
                JsonConvert.DeserializeObject<TAggregate>(json)
            );
        }

        public async Task SaveAsync(TAggregate aggregate)
        {
            var key = _storageKey + aggregate.Id.ToString();
            var json = JsonConvert.SerializeObject(aggregate);
            
            PlayerPrefs.SetString(key, json);
            PlayerPrefs.Save();

            await Task.CompletedTask;
        }

        public async Task DeleteAsync(TId id)
        {
            var key = _storageKey + id.ToString();
            PlayerPrefs.DeleteKey(key);
            PlayerPrefs.Save();

            await Task.CompletedTask;
        }
    }
}
